package com.axialproject.health.exchange.demo;

import com.axialproject.health.exchange.EMF;
import com.axialproject.health.exchange.PatientManager;
import com.axialproject.health.exchange.entity.Patient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 *
 * @author Michael Yuan
 */
public class IndexFilter implements Filter {

    private static final Logger log = Logger.getLogger(IndexFilter.class.getName());

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        String appUrl = filterConfig.getServletContext().getInitParameter("AppUrl");

        EntityManager em = EMF.get().createEntityManager();
        try {
            List <Patient> patients = PatientManager.getPatientsByAppName(em, "ringful-demo");
            List <String> usernames = new ArrayList <String> ();
            for (Patient patient : patients) {
                usernames.add (patient.getUsername());
            }
            req.setAttribute("users", usernames);
        } finally {
            em.close ();
        }

        chain.doFilter(req, resp);

        /*
        HttpSession session = ((HttpServletRequest) req).getSession(true);
        String username = (String) session.getAttribute("username");

        if (username != null) {
            try {
                Patient patient = PatientManager.getPatientByUsernameProviderName(username, "ringful-demo");
                List <Patient> patients = PatientManager.getPatientsByMasterPatientId(patient.getMasterPatientId());

                if (patients == null || patients.size() == 0) {
                    // This user account is NOT associated with a google account
                    req.setAttribute("GoogleStatus", "This account is not connected to a Google Health account. " + createGoogleAuth(patient.getId()));
                } else {
                    // TODO: We need to deal with multiple Google accounts associated with the same account
                    
                    // Test if the token is valid in Google
                    boolean validToken = false;
                    try {
                        Map<String, String> tokenInfo = AuthSubUtil.getTokenInfo(patients.get(0).getToken(), null);
                        if (tokenInfo != null) {
                            validToken = true;
                        }
                    } catch (Exception te) {
                        log.log(Level.SEVERE, te.getMessage(), te);
                    }

                    if (validToken) {
                        req.setAttribute("GoogleStatus", "This account is connected to Google account " + patients.get(0).getEmail());
                    } else {
                        req.setAttribute("GoogleStatus", "It seems that the Google access token is no longer valid for this account. " + createGoogleAuth(patient.getId()));
                    }

                }

            } catch (Exception e) {
                log.log(Level.SEVERE, e.getMessage(), e);
            }

            chain.doFilter(req, resp);

        } else {
            ((HttpServletResponse) resp).sendRedirect("/demo/login.jsp");
        }
        */
    }

    /*
    private String createGoogleAuth (Long patientId) {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        if (user == null) {
            String nextUrl = appUrl + "/google/after_login?authMode=session&patientId=" + patientId;
            return "<a href=\"" + userService.createLoginURL(nextUrl) + "\">Log into Google to connect your account to Google</a>";
        } else {
            String nextUrl = appUrl + "/google/confirm?authMode=session&patientId=" + patientId;
            String scope = "http://www.google.com/health/feeds/";
            boolean secure = false;  // set secure=true to request secure AuthSub tokens
            boolean session = true;
            String authSubUrl = AuthSubUtil.getRequestUrl(nextUrl, scope, secure, session);
            return "<a href=\"" + authSubUrl + "\">Connect your account to Google account for " + user.getEmail() + "</a>";
        }
    }
    */

    private FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void destroy() {
        this.filterConfig = null;
    }

}

